<?php 
class TestsController extends AppController {
    public $name = 'Tests';
    
    public function beforeFilter() {
        $this->Auth->allow('view', 'mixed');
    }
    
    public function isAuthorized($user) {
        $this->loadModel('User');
        $this->User->id = $user['id'];
        $this->User->unbindModel(array('hasMany' => array('Test')));
        $role = $this->User->read('role');
        if($role['User']['role'] == 'none') {
            if(in_array($this->action, array('add', 'share', 'notshare', 'delete', 'view', 'edit', 'edithead', 'like', 'dislike', 'viewall'))) {
                return true;
            }
        }
        if($role['User']['role'] == 'admin') {
            if(in_array($this->action, array('add', 'share', 'notshare', 'delete', 'view', 'edit', 'edithead', 'like', 'dislike', 'viewall'))) {
                return true;
            }
        }
    }
    
    public function share($id) {
        $this->Test->id = $id;
        
        $user = $this->Test->read(array('user_id'));
        
        if($this->Test->exists() && $this->Auth->user('id') == $user['Test']['user_id']) {
            $test['Test']['share'] = 1;
            
            if($this->Test->save($test)) {                
                $this->Session->setFlash('Chia sẽ mã đề '.$id.' thành công');
                $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
            } else {
                $this->Session->setFlash('Chia sẽ mã đề '.$id.' không thành công');
                $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
            }
        } else {
            $this->Session->setFlash('Không thể chia sẽ mã đề '.$id);
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
    }
    
    public function notshare($id) {
        $this->Test->id = $id;
        
        $user = $this->Test->read(array('user_id'));
        
        if($this->Test->exists() && $this->Auth->user('id') == $user['Test']['user_id']) {
            $test['Test']['share'] = 0;
            
            if($this->Test->save($test)) {              
                $this->Session->setFlash('Hủy chia sẽ mã đề '.$id.' thành công');
                $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
            } else {
                $this->Session->setFlash('Hủy chia sẽ mã đề '.$id.' không thành công');
                $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
            }
        } else {
            $this->Session->setFlash('Không thể hủy chia sẽ mã đề '.$id);
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
    }
    
    public function add($step, $subjectId = 0) {
        $this->set('title_for_layout', 'Tạo Đề Mới :: ChomoTech');
    
        if($step) {
            switch($step) {
                case 'step1':
                    $this->set('step', 'step1');
                    break;
                case 'step2':
                    $this->set('step', 'step2');
                    $this->loadModel('Subject'); $this->Subject->id = $subjectId;
                    if($this->Subject->exists()) {
                        $this->set('subjectId', $subjectId);
                        if($this->request->is('post')) {
                            App::import('Vendor', 'ChomoClass');
                            $this->request->data['Test']['id'] = $this->random_id();
                            $this->request->data['Test']['subject_id'] = $subjectId;
                            $this->request->data['Test']['user_id'] = $this->Auth->user('id');
                            if($this->Test->save($this->request->data['Test'], true, array('id', 'user_id', 'grade_id', 'subject_id', 'name'))) {
                                $this->Session->setFlash('Tạo đề thành công.');
                                $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
                            }
                        }
                    } else {
                        $this->redirect(array('controller' => 'tests', 'action' => 'add', 'step1'));
                    }
                    break;
                default:
                    $this->redirect(array('controller' => 'tests', 'action' => 'add', 'step1'));
                    break;
            }
        } else {
            $this->redirect(array('controller' => 'tests', 'action' => 'add', 'step1'));
        }
    }
    
    public function random_id() {
        $data = strtoupper(ChomoClass::random_char());
        if($this->Test->find('count', array('conditions' => array('Test.id' => $data)))) {
            $this->random_id();
        }
        return $data;
    }
    
    public function viewall($subjectId = null){
        $this->set('title_for_layout', 'Đề Cá Nhân :: ChomoTech');
        
        $this->Test->unbindModel(array('hasMany' => array('Question')));
        
        $this->paginate = array(
            'Test' => array(
                'limit' => 10,
                'order' => array('created' => 'desc')
            )
        );
        $this->loadModel('User');
        $this->User->id = $this->Auth->user('id');
        
        $this->Test->unbindModel(array('hasMany' => array('Like')));
        $tests = $this->Test->find('all', array('conditions' => array('Test.user_id' => $this->User->id), 'fields' => array('Test.id', 'Subject.id', 'Subject.name')));
        
        $subjects = array();
        foreach($tests as $test) {
            if(!in_array($test['Subject'], $subjects)) {
                array_push($subjects, $test['Subject']);
            }
        }
        
        $this->set('testSubjectView', $subjects);
        
        if($this->User->exists()) {
            if($subjectId) {
                $this->loadModel('Subject');
                $this->Subject->id = $subjectId;
                if($this->Subject->exists()) {
                    $this->set('subjectDir', $this->Subject->read(array('name')));
                    $this->set('test', $this->paginate('Test', array('Test.user_id' => $this->User->id, 'Test.subject_id' => $subjectId)));
                } else {
                    $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
                }
            } else {
                $this->set('test', $this->paginate('Test', array('Test.user_id' => $this->User->id)));
            }
        }
    }
    
    public function delete($id) {
        $test = $this->Test->read(array('user_id', 'question_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
        }
        
        $this->set('title_for_layout', 'Xóa Đề :: ChomoTech');
        $this->Test->id = $id;
        $this->set('id', $id);
        
        $user = $this->Test->read(array('user_id'));
        
        if($this->Test->exists() && $this->Auth->user('id') == $user['Test']['user_id']) {
            
            if($this->request->is('post')) {
                 
                if($this->Test->delete()) {
                    $this->Session->setFlash('Xóa thành công đề '.$id);
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
                } else {
                    $this->Session->setFlash('Không thể xóa '.$id);
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
                }
            }
            
        } else {
            $this->Session->setFlash('Không thể xóa '.$id);
             
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
    }
    
    public function view($id) {
        $this->Session->delete('chomo.Question.Nums');
        
        $this->Test->id = $id;
        
        if($this->Test->exists()) {
            $this->Test->unbindModel(array('hasMany' => array('Like', 'Question')));

            $test = $this->Test->read();
            $this->set('title_for_layout', $test['Test']['name'].' :: ChomoTech');
            if($test['Test']['share'] == 0 && $test['Test']['user_id'] != $this->Auth->user('id')) {
                 
                $this->redirect(array('controller' => 'index', 'action' => 'index'));
            }
            if($test['Test']['user_id'] == $this->Auth->user('id')) {
                $this->set('right_user', true);
            }

            $this->set('test', $test);

            $this->loadModel('Question');
            $this->Question->unbindModel(array('belongsTo' => array('Test')));
            $this->set('questionTestView', $this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'test'))));
            $this->set('questionNormalView', $this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'normal'))));
            
            $this->Test->unbindModel(array('hasMany' => array('Question', 'Like'), 'belongsTo' => array('Subject', 'Grade')));
            $share = $this->Test->read('share');
            if($share['Test']['share'] == 1) {
                $this->loadModel('Discussion');
                $this->set('discussionView', $this->Discussion->find('all', array('conditions' => array('test_id' => $id), 'order' => 'created ASC')));
                $this->set('user_id', $this->Auth->user('id'));
            }
        } else {
            $this->Session->setFlash('Mã đề '.$id.' không tồn tại.');
             
            $this->redirect(array('controller' => 'index'));
        }
    }
    
    public function edit($id) {
        $test = $this->Test->read(array('user_id', 'question_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
        }
        
        $this->Session->delete('chomo.Question.Nums');
        
        $this->Test->id = $id;
        
        if($this->Test->exists()) {
            $test = $this->Test->read();
            $this->set('title_for_layout', 'Chỉnh sửa '.$test['Test']['name'].' :: ChomoTech');
            if($test['Test']['user_id'] == $this->Auth->user('id')) {
                $this->set('right_user', true);
            }

            $this->set('test', $test);

            $this->loadModel('Question');
            $this->Question->unbindModel(array('belongsTo' => array('Test')));
            $this->set('questionTestView', $this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'test'))));
            $this->set('questionNormalView', $this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'normal'))));
            
        } else {
            $this->Session->setFlash('Mã đề '.$id.' không tồn tại.');
             
            $this->redirect(array('controller' => 'index'));
        }
    }
    
    public function edithead($id) {
        $test = $this->Test->read(array('user_id', 'question_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
        }
        
        $this->set('title_for_layout', 'Chỉnh sửa :: ChomoTech');
        
        $this->Test->id = $id;
        
        if($this->Test->exists()) {
            $this->loadModel('Grade');
            
            $this->Grade->unbindModel(array('hasMany' => array('Test')));
            
            $this->set('gradeView', $this->Grade->find('all'));
            
            $test = $this->Test->read();
            
            if($test['Test']['user_id'] == $this->Auth->user('id')) {
                $this->set('right_user', true);
            }
            $this->set('test', $test);
            if($this->request->is('post')) {
                 
                if($this->Test->save($this->request->data, true, array('grade_id', 'name'))) {
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'edit', $test['Test']['id']));
                }
            }
        } else {
            $this->Session->setFlash('Mã đề '.$id.' không tồn tại.');
             
            $this->redirect(array('controller' => 'index'));
        }
    }
    
    public function mixed($id) {
        $this->Session->delete('chomo.Question.Nums');
        if($this->Session->check('mixedTimes') == false) {
             
        } else if(time() - (int)$this->Session->read('mixedTimes') < 1) {
             
             
            $this->redirect(array('controller' => 'error', 'action' => 'fasterror'));
        }
         
        
        $this->Test->id = $id;
        
        if($this->Test->exists()) {

            $test = $this->Test->read();
            $this->set('title_for_layout', 'Trộn '.$test['Test']['name'].' :: ChomoTech');
            if($test['Test']['user_id'] == $this->Auth->user('id')) {
                $this->set('right_user', true);
            }

            $this->set('test', $test);
            
            $this->loadModel('Question');
            $this->Question->unbindModel(array('belongsTo' => array('Test')));
            $questionsTest = $this->chomo_mixed($this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'test'))));
            $questionsNormal = $this->chomo_mixed($this->Question->find('all', array('conditions' => array('test_id' => $id, 'type' => 'normal'))));
           
            $i = 0;
            $label = array('A','B','C','D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            foreach($questionsTest as $question) {
                $questionsTest[$i]['Answer'] = $this->chomo_mixed($questionsTest[$i]['Answer']);
                $j = 0;
                    foreach($question['Answer'] as $answer) {
                        $questionsTest[$i]['Answer'][$j]['label'] = $label[$j];
                        $j++;
                    }
                $i++;
            }
            $this->set('questionTestView', $questionsTest);
            $this->set('questionNormalView', $questionsNormal);
            
        } else {
            $this->Session->setFlash('Mã đề '.$id.' không tồn tại.');
             
            $this->redirect(array('controller' => 'index'));
        }
    }
    
    function chomo_mixed($array)
    {
        $result = array();
        while($array)
        {
            $num = array_rand($array);
            array_push($result, $array[$num]);
            unset($array[$num]);
        }
        return $result;
    }
    
    public function like($id) {
        $this->Test->id = $id;
        if($this->Test->exists()) {
            $this->Test->unbindModel(array('hasMany' => array('Question', 'Like'), 'belongsTo' => array('Subject')));
            $test = $this->Test->read();
            
            if($test['Test']['user_id'] != $this->Auth->user('id')) {
                $this->loadModel('Like');
                if(!$this->Like->find('count', array('conditions' => array('user_id' => $this->Auth->user('id'), 'test_id' => $id)))) {
                    $like['Like']['user_id'] = $this->Auth->user('id');
                    $like['Like']['test_id'] = $id;
                    $test['Test']['like'] = (int)$test['Test']['like'] + 1;
                    
                    if($this->Test->save($test) && $this->Like->save($like)) {
                         
                        $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                    } else {
                         
                        $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                    }
                } else {
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                }
            } else {
                 
                $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
            }
        } else {
             
            $this->redirect(array('controller' => 'index'));
        }
    }
    
    public function dislike($id) {
        $this->Test->id = $id;
        if($this->Test->exists()) {
            $this->Test->unbindModel(array('hasMany' => array('Question', 'Like'), 'belongsTo' => array('Subject')));
            $test = $this->Test->read();
            
            if($test['Test']['user_id'] != $this->Auth->user('id')) {
                $this->loadModel('Like');
                if(!$this->Like->find('count', array('conditions' => array('user_id' => $this->Auth->user('id'), 'test_id' => $id)))) {
                    $like['Like']['user_id'] = $this->Auth->user('id');
                    $like['Like']['test_id'] = $id;
                    $test['Test']['dislike'] = (int)$test['Test']['dislike'] + 1;
                    
                    if($this->Test->save($test) && $this->Like->save($like)) {
                         
                        $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                    } else {
                         
                        $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                    }
                } else {
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
                }
            } else {
                 
                $this->redirect(array('controller' => 'tests', 'action' => 'view', $id));
            }
        } else {
             
            $this->redirect(array('controller' => 'index'));
        }
    }
}
?>